<template>
  <el-dialog :title="title"
             :visible.sync="visible"
             v-loading="loading"
             :before-close="modalClose"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="50%">
    <el-form :model="formModel"
             label-position="right"
             ref="formModelRef"
             label-width="180px"
             :rules='formModelRules'>
      <el-form-item label="病种名称："
                    prop="name">
        <el-input v-model="formModel.name"
                  clearable
                  class="w-200"
                  placeholder="请输入病种名称"></el-input>
      </el-form-item>
      <el-form-item label="前置条件：">
        <el-select v-model="formModel.beforeConditionCode"
                   clearable
                   class="w-200"
                   placeholder="请选择前置条件">
          <el-option v-for="item in qianzhiData"
                     :key="item.id"
                     :label="item.content"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="确认方式：">
        <el-checkbox-group v-model="formModel.confirmTypes" @change="handlerCheck()">
          <el-checkbox v-for="(item,index) in boxList" :key="index" :label="item.lable.toString()"
                       :disabled="item.lable==1">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="定性量表："
                    prop="confirmScaleIds"
                    :rules="checkDingxing?formModelRules.confirmScaleIds:[{required:false}]"
                    v-if="checkDingxing">
        <el-select v-model="formModel.confirmScaleIds"
                   clearable
                   multiple
                   style="width:400px"
                   placeholder="请选择（可多选）">
          <el-option v-for="item in liangbiaoData"
                     :key="item.id"
                     :label="item.scaleName"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联沃慧管病类："
                    prop="drugDiseaseId"
                    :rules="checkWohui?formModelRules.drugDiseaseId:[{required:false}]"
                    v-if="checkWohui">
        <el-select v-model="formModel.drugDiseaseId"
                   clearable
                   filterable
                   class="w-200"
                   @change="handleChangeType()"
                   placeholder="请选择关联沃慧管病类">
          <el-option v-for="item in binglei"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="关联沃慧管病种："
                    v-if="checkWohui">
        <el-select v-model="formModel.drugDiseaseItemIds"
                   clearable
                   multiple
                   class="w-200"
                   placeholder="请选择关联沃慧管病种">
          <el-option v-for="item in bingzhong"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="需填写内容："
                    prop="indexItems"
                    :rules="checkTiaojian?formModelRules.indexItems:[{required:false}]"
                    v-if="checkTiaojian">
        <el-select v-model="formModel.indexItems"
                   clearable
                   multiple
                   class="w-200"
                   placeholder="请选择内容">
          <el-option v-for="item in zhibiaoData"
                     :key="item.id"
                     :label="item.name+item.unit"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否必填:" class="is-required" v-if="checkTiaojian">
        <el-radio-group v-model="formModel.indexNeedAll">
          <el-radio :label="1">全部必填</el-radio>
          <el-radio :label="0">任填一项</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="条件判断："
                    v-if="checkTiaojian">
        <el-button type="primary" @click="handleAddTiaojian">增 加</el-button>
      </el-form-item>


      <el-form-item v-if="checkTiaojian&&formModel.conditions.length>0">
        <element-table :columns="columnsCondition"
                       :data="formModel.conditions">
          <template v-slot:firstValue="{row}">
            <el-input v-model="row.firstValue"
                      placeholder="左边值"
                      clearable/>
          </template>
          <template v-slot:firstCondition="{row}">
            <el-select v-model="row.firstCondition"
                       clearable
                       placeholder="关系">
              <el-option v-for="item in fuhaoLeft"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </template>
          <template v-slot:indexItemId="{row}">
            <el-select v-model="row.indexItemId"
                       clearable
                       placeholder="指标">
              <el-option v-for="item in zhibiaoData"
                         :key="item.id"
                         :label="item.name+item.unit"
                         :value="item.id">
              </el-option>
            </el-select>
          </template>
          <template v-slot:secondCondition="{row}">
            <el-select v-model="row.secondCondition"
                       clearable
                       class="w-100"
                       :disabled="row.firstCondition==1"
                       placeholder="关系">
              <el-option v-for="item in fuhaoRight"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </template>
          <template v-slot:secondValue="{row}">
            <el-input v-model="row.secondValue"
                      clearable
                      placeholder="右边值"
                      :disabled="row.firstCondition==1"/>
          </template>

          <template v-slot:option="{row,index}">
            <el-button type="danger"
                       @click="handlerDeleteTiaojian(index)">删除
            </el-button>
          </template>

        </element-table>
      </el-form-item>

      <el-form-item label="条件关系：" v-if="checkTiaojian">

        <el-select v-model="formModel.conditionType"
                   clearable
                   class="w-200"
                   placeholder="请选择关系">
          <el-option v-for="item in guanxi"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="关于健康地图："
                    prop="aboutContent">
        <el-input v-model="formModel.aboutContent"
                  clearable
                  style="width: 400px;"
                  size="medium"
                  type="textarea"
                  autosize
                  placeholder="健康地图"></el-input>
      </el-form-item>
      <el-form-item label="包含量表：" class="is-required">
        <el-select v-model="includeScale"
                   clearable
                   value-key="id"
                   filterable
                   style="width: 300px"
                   placeholder="请选择量表">
          <el-option v-for="item in liangbiaoData"
                     :key="item.id"
                     :label="item.scaleName"
                     :value="item">
          </el-option>
        </el-select>
        <el-input v-model="includeScaleSort"
                  clearable
                  class="w-200"
                  type="number"
                  placeholder="请输入排序"></el-input>
        <el-button type="primary" @click="handleAddScale">增 加</el-button>
      </el-form-item>
      <el-form-item prop="scalePool">
        <element-table :columns="columnsScale"
                       :isShowNull="false"
                       :data="formModel.scalePool">
          <template v-slot:sortNum="{row,index}">
            <el-input v-model="row.sortNum" type="number" placeholder="请输入排序"></el-input>
          </template>
          <template v-slot:option="{row,index}">
            <el-button type="danger"
                       @click="handlerDelScale(index)">删除
            </el-button>
          </template>

        </element-table>

      </el-form-item>

      <el-form-item label="高危共病：">
        <el-select v-model="formModel.themes"
                   filterable
                   remote
                   value-key="id"
                   clearable
                   multiple
                   placeholder="请输入慢病"
                   :remote-method="searchMethod"
                   :loading="searchLoading"
                   class="w-300">
          <el-option v-for="item in diseaseListData"
                     :key="item.id"
                     :label="item.name"
                     :value="item">
          </el-option>
        </el-select>
      </el-form-item>



    </el-form>
    <p align="center">
      <el-button @click="modalClose"
                 type="info">取 消
      </el-button>
      <el-button type="primary"
                 v-prevent-re-click
                 @click="submitForm()">保 存
      </el-button>
    </p>
  </el-dialog>
</template>
<script>
import ElementTable from '@/base/ElementTable'

export default {
  name: 'diseaseDialog', // 病种管理
  props: {
    dataObj: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columnsScale: [
        {
          label: '量表名称',
          prop: 'scaleName',
          align: 'center',
        },
        {
          label: '前端排序',
          prop: 'sortNum',
          align: 'center',
          isSlot: true,
          width: 100
        },
        {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true,
          width: 100
        }
      ],
      columnsCondition: [
        {
          label: '左边项',
          prop: 'firstValue',
          align: 'center',
          isSlot: true
        },
        {
          label: '关系',
          prop: 'firstCondition',
          align: 'center',
          isSlot: true
        },
        {
          label: '指标',
          prop: 'indexItemId',
          align: 'center',
          isSlot: true
        },
        {
          label: '关系',
          prop: 'secondCondition',
          align: 'center',
          isSlot: true
        },
        {
          label: '右边项',
          prop: 'secondValue',
          align: 'center',
          isSlot: true
        },
        {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true,
        }
      ],
      boxList: [
        {
          name: '手动',
          lable: '1'
        },
        {
          name: '条件判断',
          lable: '2'
        },
        {
          name: '量表',
          lable: '3'
        },
        {
          name: '关联沃慧管病种',
          lable: '4'
        }
      ],

      guanxi: [
        {
          name: '全部满足',
          id: 1
        },
        {
          name: '任一满足',
          id: 2
        }, {
          name: '满足任何两个',
          id: 3
        }],
      num: 0,
      //新增字段
      fuhaoRight: [{
        name: '<',
        id: 4
      }, {
        name: '<=',
        id: 5
      }
      ],
      fuhaoLeft: [
        {
          name: '=',
          id: 1
        }, {
          name: '<',
          id: 4
        }, {
          name: '<=',
          id: 5
        }],
      checkTiaojian: false,
      checkDingxing: false,
      checkWohui: false,

      //病种
      bingzhong: [],
      title: '新 增',
      loading: false,
      searchLoading: false,
      //主数据
      formModel: {
        id: '',
        name: '',
        aboutContent: '',
        confirmTypes: ['1'],
        conditions: [],
        scalePool: [],
        beforeConditionCode: '',
        conditionType: '',
        indexItems: [],
        confirmScaleIds: [],
        drugDiseaseId: '',
        drugDiseaseItemIds: [],
        indexNeedAll: 1,
        themes: [],
      },
      includeScale: '',
      includeScaleSort: '',
      //指标数据
      zhibiaoData: [],
      //量表数据
      liangbiaoData: [],
      diseaseListData: [],
      //前置条件数据
      qianzhiData: [],
      //病类
      binglei: [],
      formModelRules: {
        name: [
          {required: true, message: '请输入病种名称', trigger: 'blur'},
        ],
        aboutContent: [
          {required: true, message: '请输入关于健康地图', trigger: 'blur'},
        ],
        drugDiseaseId: [
          {required: true, message: '请选择病类', trigger: 'blur'},
        ],
        scalePool: [
          {type: 'array', required: true, message: '请添加量表', trigger: 'blur'},
        ],
        indexItems: [
          {type: 'array', required: true, message: '请选择内容', trigger: 'change'},
        ],
        confirmScaleIds: [
          {type: 'array', required: true, message: '请选择定性量表', trigger: 'change'},
        ],
      },


    }
  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    //搜索指标项
    searchMethod(query) {
      if (query !== '') {
        let _this = this;
        _this.searchLoading = true; // 锁住
        this.post(this.api.healthMap.getChronicList, {
          searchCondition: query,
        }).then(res => {
          if (res.data.code === '200') {
            _this.searchLoading = false;
            _this.diseaseListData = res.data.object;
          }
        })

      } else {
        this.diseaseListData = [];
      }
    },
    //添加量表
    handleAddScale() {
      if (this.includeScale.id && this.includeScaleSort) {
        let scalePool = this.formModel.scalePool;
        let map = scalePool.map(item => item.sortNum).map(String);
        if (scalePool.length > 0) {
          if (map.filter(item => item).indexOf(this.includeScaleSort) !== -1) {
            this.$message.warning('前端排序重复')
          } else if (scalePool.map(item => item.scaleId).indexOf(this.includeScale.id) !== -1) {
            this.$message.warning('量表已存在')
          } else {
            scalePool.push({
              scaleId: this.includeScale.id,
              scaleName: this.includeScale.scaleName,
              sortNum: this.includeScaleSort
            })
            this.includeScale = ''
            this.includeScaleSort = ''
          }
        } else {
          scalePool.push({
            scaleId: this.includeScale.id,
            scaleName: this.includeScale.scaleName,
            sortNum: this.includeScaleSort
          })
          this.includeScale = ''
          this.includeScaleSort = ''
        }
      } else {
        this.$message.warning('请选择量表输入排序')
      }
    },
    //删除量表
    handlerDelScale(index) {
      this.formModel.scalePool.splice(index, 1)
    },
    //种类多选事件
    handlerCheck() {
      this.handleShowChip(this.formModel.confirmTypes)
    },

    //新增条件
    handleAddTiaojian() {
      var list = this.formModel.conditions
      var data = {
        indexItemId: '',
        firstCondition: '',
        firstValue: '',
        indexItemName: '',
        secondCondition: '',
        secondValue: '',
      }
      list.push(data)


    },
    //删除条件
    handlerDeleteTiaojian(index) {
      var list = this.formModel.conditions
      list.splice(index, 1)
    },

    //获取病症详情
    getDetail() {
      this.post(this.api.healthMap.getHealthMapDiseaseDetail, {id: this.dataObj.id}).then((res) => {
        if (res.data.code === '200') {
          let bean = res.data.object
          if (bean.confirmTypes) {
            this.formModel.confirmTypes = bean.confirmTypes.split('').join(',').split(',')
            this.handleShowChip(this.formModel.confirmTypes)
          }
          if (bean.scales) {
            this.formModel.scalePool = bean.scales.filter(item => item.type == 1)
            this.formModel.confirmScaleIds = bean.scales.filter(item => item.type == 2).map(item => item.scaleId)
          }

          this.formModel.conditions = bean.conditions ? res.data.object.conditions : []
          this.formModel.conditions = this.formModel.conditions.filter(item => item)
          this.formModel.id = bean.id
          this.formModel.name = bean.name
          this.formModel.indexNeedAll = bean.indexNeedAll

          if (bean.drugDiseaseType) {
            this.formModel.drugDiseaseId = bean.drugDiseaseType.id
          }
          if (bean.drugDiseaseItems) {
            this.formModel.drugDiseaseItemIds = bean.drugDiseaseItems.map(item => item.id)
          }
          if (bean.items) {
            this.formModel.indexItems = bean.items.map(item => item.id)
          }
          if (bean.conditionType) {
            this.formModel.conditionType = bean.conditionType
          }
          this.formModel.aboutContent = bean.aboutContent
          this.formModel.beforeConditionCode = bean.beforeConditionCode

          if (this.formModel.drugDiseaseId) {
            this.getHealthMapItems()
          }
          if (bean.themes && bean.themes.length > 0) {
            this.diseaseListData = bean.themes.map(o => ({
              id: o.themeId,
              name: o.themeName
            }))
            this.formModel.themes=bean.themes.map(o => ({
              id: o.themeId,
              name: o.themeName
            }))
          } else {
            this.formModel.themes = []
          }
        }
      })
    },
    //显示组件
    handleShowChip(confirmTypes) {
      this.checkTiaojian = confirmTypes.some(item => item == '2');
      this.checkDingxing = confirmTypes.some(item => item == '3');
      this.checkWohui = confirmTypes.some(item => item == '4');
    },
    //获取病症详情
    getHealthMapIndexItemList() {
      this.post(this.api.healthMap.getHealthMapIndexItemList).then((res) => {
        if (res.data.code === '200') {
          this.zhibiaoData = res.data.object
        }
      })
    },
    //量表查询
    getScaleAll() {
      this.post(this.api.healthMap.getScaleAll, {
        pageSize: 300
      }).then((res) => {
        if (res.data.code === '200') {
          this.liangbiaoData = res.data.object
        }
      })
    },

    //前置条件查询
    getBeforeConditions() {
      this.post(this.api.healthMap.getBeforeConditions).then((res) => {
        if (res.data.code === '200') {
          this.qianzhiData = res.data.object
        }
      })
    },
    //病类查询
    getHealthMapTypes() {
      this.post(this.api.healthMap.getHealthMapTypes).then((res) => {
        if (res.data.code === '200') {
          this.binglei = res.data.object
        }
      })
    },
    //病类选择
    handleChangeType() {
      this.formModel.drugDiseaseItemIds = null
      if (!this.formModel.drugDiseaseId) {
        this.bingzhong = null
      } else {
        this.getHealthMapItems()
      }
    },
    //病种查询
    getHealthMapItems() {
      this.post(this.api.healthMap.getHealthMapItems, {
        drugDiseaseTypeId: this.formModel.drugDiseaseId
      }).then((res) => {
        if (res.data.code === '200') {
          this.bingzhong = res.data.object
        }
      })
    },
    //提交
    updateHealthMapDisease(myData) {
      this.loading = true
      this.post(this.api.healthMap.updateHealthMapDisease, myData).then((res) => {
        this.loading = false
        if (res.data.code === '200') {
          this.$message.success('保存成功!');
          this.$parent.getList(); // 调用父件组方法
          this.modalClose();
        }
      })
    },
    // 保存
    submitForm() {
      this.$refs.formModelRef.validate(async (valid) => {
        if (valid) {
          let formModel = this.formModel
          let myData = JSON.stringify(formModel)
          myData = JSON.parse(myData)
          myData.themes = myData.themes.map(o => ({
            themeId: o.id
          }))
          myData.confirmTypes = myData.confirmTypes.toString()
          myData.confirmTypes = myData.confirmTypes.replace(/,/g, '')
          this.updateHealthMapDisease(myData)
        }
      })
    },

  },
  created() {
    this.getHealthMapIndexItemList()
    this.getScaleAll()
    this.getBeforeConditions()
    this.getHealthMapTypes()
    if (this.dataObj) {
      this.title = '编 辑'
      this.getDetail()
      this.formModel.id = this.dataObj.id
    } else {
      //新增
    }


  },
  components: {
    'element-table': ElementTable,
  }


}
</script>
<style scoped lang="scss">
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.w-100 {
  width: 100px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
